import Vue from 'vue'
import VueRouter from 'vue-router'

//导入路由
import login from '@/views/user/login.vue'
import layout from '@/views/layout.vue'
import home from '@/views/home/home.vue'
import qa from '@/views/qa/qa.vue'
import movie from '@/views/movie/movie.vue'
import user from '@/views/user/user.vue'
import notfound from '@/views/notfound/notfound.vue'

Vue.use(VueRouter)

const routes = [
  {
    name: 'login',
    path: '/login',
    component: login
  },
  // 二级路由
  {
    name: 'layout',
    path: '/',
    component: layout,
    children: [
      {
        name: 'home',
        path: '/home',
        component: home,
      },
      {
        name: 'qa',
        path: '/qa',
        component: qa,
      },
      {
        name: 'movie',
        path: '/movie',
        component: movie,
      },
      {
        name: 'user',
        path: '/user',
        component: user,
        // 路由元信息
        meta: { isLogin : true }
      },
      {
        path: '/',
        redirect: '/home'
      }
    ]
  },
  {
    name: 'notfound',
    path: '/notfound',
    component: notfound
  },
  {
    path: '*',
    redirect: '/notfound'
  }
]

const router = new VueRouter({
  routes
})

//导入token文件
import { getToken } from '@/utils/token.js'

// 在生成路由之后制定路由守卫
router.beforeEach((to, from, next) => {
  // 判断路由元是否存在存在,判断token是否存在
  if (to.meta.isLogin && !getToken()) {
    next({ path: '/login' })
  } else {
    next()
  }
})

export default router
